﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

public partial class CustomerManagement_LineOfCreditManagementDetails : System.Web.UI.Page
{
    TextBox txtNote;
    private string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"].ToString() : "";
        }
    }

    private DataSet DstDetails
    {
        get
        {
            DataSet dstDetails = null;
            if (ViewState["DstDetails"] != null)
            {
                dstDetails = (DataSet)ViewState["DstDetails"];
            }
            return dstDetails;
        }
        set
        {
            ViewState["DstDetails"] = value;
        }
    }

    private bool IsAudit
    {
        get
        {
            bool isAudit = false;
            if (ViewState["IsAudit"] != null)
            {
                isAudit = Convert.ToBoolean(ViewState["IsAudit"]);
            }
            return isAudit;
        }
        set
        {
            ViewState["IsAudit"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("300400100");
        if (!IsPostBack)
        {
            BindMain();
            BindDetails();
            if (this.IsAudit)
            {
                btnAudit.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnAddDetail.Enabled = false;
            }
        }

        Session["FCode"] = "300400100";
    }

    private void BindMain()
    {
        DataSet dst = new BLL.CREDITADJUST().GetMainById(this.Code);
        if (dst.Tables[0].Rows.Count > 0)
        {
            this.IsAudit = dst.Tables[0].Rows[0]["CA_CHECK"].ToString() == "1" ? true : false;
        }
        dlistMain.DataSource = dst; 
        dlistMain.DataBind();
    }

    private void BindDetails()
    {
        this.DstDetails = new BLL.CREDITADJUSTDETAIL().GetDetailsById(this.Code);
        dlistDetail.DataSource = this.DstDetails;
        dlistDetail.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400100", "00017"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.CREDITADJUST ca = new BLL.CREDITADJUST().GetModel(this.Code);
            if (ca != null)
            {
                if (ca.CA_CHECK == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            SetValueOfDataTable(this.DstDetails);
            if (this.DstDetails.Tables[0].Rows.Count == 0)
            {
                throw new Exception("请选择您要调整的会员！");
            }
            if (new BLL.CREDITADJUST().Save(this.Code, this.DstDetails, ((TextBox)dlistMain.Items[0].FindControl("txtNote")).Text))
            {
                Share.InsertLog("300400100", "00017");
                Share.Alert(this.Page,"保存成功！");
            }
            else
            {
                Share.Alert(this.Page, "保存失败，请重新尝试保存！");
            }

        }
        catch (Exception ex)
        {
            Share.Alert(this.Page,ex.Message);
        }
    }

    protected void btnAudit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400100", "00010"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.CREDITADJUST ca = new BLL.CREDITADJUST().GetModel(this.Code);
            if (ca != null)
            {
                if (ca.CA_CHECK == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            DataSet dstDetails = new BLL.CREDITADJUSTDETAIL().GetDetails(this.Code);
            StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
            StringBuilder strSqlToUpdateErpDB = new StringBuilder();
            char[] charToTrim = new char[] { '|' };
            string strCommandOfBStyle;
            string strCommandOfErp;
            string strWebServiceKey = ConfigurationManager.AppSettings["WebServiceKey"].ToString();
            string[] strArraySqlCommandArrayToUpdateBStyleDB;
            string[] strArraySqlCommandArrayToUpdateErpDB;

            for (int i = 0; i < dstDetails.Tables[0].Rows.Count; i++)
            {
                if (dstDetails.Tables[0].Rows[i]["AccountBalance"].ToString() == "")
                {
                    strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                    strSqlToUpdateBStyleDB.Append(dstDetails.Tables[0].Rows[i]["VIPCODE"].ToString());
                    strSqlToUpdateBStyleDB.Append("',0)|");

                    strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                    strSqlToUpdateErpDB.Append(dstDetails.Tables[0].Rows[i]["VIPCODE"].ToString());
                    strSqlToUpdateErpDB.Append("',0)|");
                }
            }
            if (strSqlToUpdateBStyleDB.ToString() != "")
            {
                strCommandOfBStyle = strSqlToUpdateBStyleDB.ToString();
                strCommandOfErp = strSqlToUpdateErpDB.ToString();

                
                strArraySqlCommandArrayToUpdateBStyleDB = strCommandOfBStyle.TrimEnd(charToTrim).Split(charToTrim);
                strArraySqlCommandArrayToUpdateErpDB = strCommandOfErp.TrimEnd(charToTrim).Split(charToTrim);

                LX_Manage.ERP.Service service = new LX_Manage.ERP.Service();

                bool initAccountBalanceResult = service.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, strArraySqlCommandArrayToUpdateBStyleDB, strArraySqlCommandArrayToUpdateErpDB);
                if (!initAccountBalanceResult)
                {
                    throw new Exception("您选择调整的会员中，有一个或多个会员没有结余款信息，当系统试图为起初始化结余款信息时，发生错误，请重新尝试审核！");
                }

                dstDetails = new BLL.CREDITADJUSTDETAIL().GetDetails(this.Code);

            }

            strSqlToUpdateBStyleDB = new StringBuilder();
            strSqlToUpdateErpDB = new StringBuilder();
            string user = Share.UserValue(0);
           
            for (int i = 0; i < dlistMain.Items.Count; i++)
            {
                txtNote = (TextBox)dlistMain.Items[i].FindControl("txtNote");
            }
                strSqlToUpdateBStyleDB.Append("update CREDITADJUST set CA_CHECK=1,CA_CHECKER='");
                strSqlToUpdateBStyleDB.Append(user);
                strSqlToUpdateBStyleDB.Append("',CA_CHECKDATE='");
                strSqlToUpdateBStyleDB.Append(DateTime.Now);
                strSqlToUpdateBStyleDB.Append("',CA_NOTE='");
                strSqlToUpdateBStyleDB.Append(txtNote.Text.Trim());
                strSqlToUpdateBStyleDB.Append("' where CA_ID='");
                strSqlToUpdateBStyleDB.Append(this.Code);
                strSqlToUpdateBStyleDB.Append("'|");
            
            for (int i = 0; i < dstDetails.Tables[0].Rows.Count; i++)
            {
                strSqlToUpdateBStyleDB.Append("update v_vipset set BYZD12=isnull(BYZD12,0)+");
                strSqlToUpdateBStyleDB.Append(dstDetails.Tables[0].Rows[i]["CAD_AMT"].ToString());
                strSqlToUpdateBStyleDB.Append(",BYZD13=");
                strSqlToUpdateBStyleDB.Append(Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["CAD_AMT"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["AccountBalance"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["BYZD12"]));
                strSqlToUpdateBStyleDB.Append(" where DM='");
                strSqlToUpdateBStyleDB.Append(dstDetails.Tables[0].Rows[i]["VIPCODE"].ToString());
                strSqlToUpdateBStyleDB.Append("'|");

                strSqlToUpdateErpDB.Append("update v_vipset set BYZD12=isnull(BYZD12,0)+");
                strSqlToUpdateErpDB.Append(dstDetails.Tables[0].Rows[i]["CAD_AMT"].ToString());
                strSqlToUpdateErpDB.Append(" where DM='");
                strSqlToUpdateErpDB.Append(dstDetails.Tables[0].Rows[i]["VIPCODE"].ToString());
                strSqlToUpdateErpDB.Append("'|");
                
            }

            strCommandOfBStyle = strSqlToUpdateBStyleDB.ToString();
            strCommandOfErp = strSqlToUpdateErpDB.ToString();

            strArraySqlCommandArrayToUpdateBStyleDB = strCommandOfBStyle.TrimEnd(charToTrim).Split(charToTrim);
            strArraySqlCommandArrayToUpdateErpDB = strCommandOfErp.TrimEnd(charToTrim).Split(charToTrim);

            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();

            bool result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, strArraySqlCommandArrayToUpdateBStyleDB, strArraySqlCommandArrayToUpdateErpDB);
            if (result)
            {
                btnAudit.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnAddDetail.Enabled = false;
                BindMain();
                BindDetails();

                Share.InsertLog("300400100", "00010");
                Share.Alert(this.Page, "审核成功！");
            }
            else
            {
                Share.Alert(this.Page,"审核失败，请重新审核！");
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page,ex.Message);
        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400100", "00003"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.CREDITADJUST ca = new BLL.CREDITADJUST().GetModel(this.Code);
            if (ca != null)
            {
                if (ca.CA_CHECK == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            bool result = new BLL.CREDITADJUST().Delete(this.Code);
            if (result)
            {
                Share.InsertLog("300400100", "00003");
                Response.Write("<script>alert('删除成功！');window.location.href='LineOfCreditManagement.aspx'</script>");
            }
            else
            {
                Response.Write("<script>alert('删除失败！');</script>");
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("LineOfCreditManagementDetails.aspx?code="+this.Code);
    }

    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("LineOfCreditManagement.aspx");
    }

    protected void dlistDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "del")
        {
            if (this.DstDetails != null)
            {
                this.DstDetails.Tables[0].Rows.RemoveAt(e.Item.ItemIndex);
                dlistDetail.DataSource = this.DstDetails;
                dlistDetail.DataBind();
            }
        }
    }

    protected void btnAddDetail_Click(object sender, EventArgs e)
    {
        try
        {
            string customerCode = hidUserCode.Value;
            if (customerCode != "")
            {
                string[] customersArray = customerCode.Split('|');
                if (customersArray.Length > 0)
                {
                    string[] customer;
                    for (int i = 0; i < customersArray.Length; i++)
                    {
                        customer = customersArray[i].Split(' ');
                        if (customer.Length == 2)
                        {
                            SetValueOfDataTable(this.DstDetails);
                            this.DstDetails = new BLL.CREDITADJUSTDETAIL().AddDataRowToDataTable(this.DstDetails, Convert.ToString(this.DstDetails.Tables[0].Rows.Count + 1), customer[0], customer[1]);
                            dlistDetail.DataSource = this.DstDetails;
                            dlistDetail.DataBind();
                        }
                    }
                }
            }
            else
            {
                return;//Share.Alert(this.Page, "请选择会员！");
            }
            hidUserCode.Value = "";
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    private void SetValueOfDataTable(DataSet dst)
    {
        Label lblDetailId;
        Label lblCustomerCode;
        Label lblCustomerName;
        TextBox txtAmount;
        TextBox txtNote;

        for (int i = 0; i < dlistDetail.Items.Count; i++)
        {
            lblDetailId = (Label)dlistDetail.Items[i].FindControl("lblDetailId");
            lblCustomerCode = (Label)dlistDetail.Items[i].FindControl("lblCustomerCode");
            lblCustomerName = (Label)dlistDetail.Items[i].FindControl("lblCustomerName");
            txtAmount = (TextBox)dlistDetail.Items[i].FindControl("txtAmount");
            txtNote = (TextBox)dlistDetail.Items[i].FindControl("txtNote");

            dst.Tables[0].Rows[i]["CAD_DETAILCODE"] = lblDetailId.Text;
            dst.Tables[0].Rows[i]["CAD_CUSTOMERCODE"] = lblCustomerCode.Text;
            dst.Tables[0].Rows[i]["GKMC"] = lblCustomerName.Text;
            dst.Tables[0].Rows[i]["CAD_AMT"] = Convert.ToDecimal(txtAmount.Text.Trim());
            dst.Tables[0].Rows[i]["CAD_NOTE"] = txtNote.Text.Trim();
        }

    }

    protected void dlistDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (this.IsAudit)
            { 
                Button btnDel = (Button)e.Item.FindControl("btnDelete");
                TextBox txtAmount = (TextBox)e.Item.FindControl("txtAmount");
                TextBox txtNote = (TextBox)e.Item.FindControl("txtNote");
                btnDel.Enabled = false;
                txtAmount.Enabled = false;
                txtNote.Enabled = false;
            }

        }
    }
}
